package com.mudrov.internetdownloader;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PageReaderByLine implements PageDownloader {

    private static Logger logger = Logger.getLogger(PageReaderByLine.class);
    private String path;
    private ArrayList<URL> urlList = new ArrayList<URL>();

    public PageReaderByLine() {
        BasicConfigurator.configure();
        Properties properties = new Properties();
        try {
            properties.load(Executor.class.getClassLoader().getResourceAsStream(Parameters.PROP_FILE_NAME.value()));
            path = properties.getProperty(Parameters.FOLDER_TO_SAVE.value());
            File toCreate = new File(path);
            toCreate.mkdir();
            path += "\\";
        } catch (IOException e) {
            logger.log(Level.FATAL, "Can`t load property file.");
            throw new RuntimeException(e);
        }
    }

    private void parseHtmlCode(String htmlCode) {
        String[] possibleLinks = htmlCode.split("\"");
        Pattern p = Pattern.compile(new StringBuilder()
                .append("((([A-Za-z]{3,9}:(?:\\/\\/)?)")
                .append("(?:[-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=")
                .append("\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)")
                .append("?\\??(?:[-\\+=&;%@.\\w_]*)#?(?:[\\w]*))?)").toString());
        for (String i : possibleLinks) {
            try {
                Matcher m = p.matcher(i);
                if (m.matches())
                    urlList.add(new URL(i));
            } catch (MalformedURLException e) {
                logger.log(Level.TRACE, "Can`t parse URL.");
            }
        }
    }

    public void readPageFromUrl(URL toRead) {
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(toRead.openStream(), "UTF-8"));
             FileWriter outputFile = new FileWriter(path + toRead.toString().hashCode() + ".html")) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                parseHtmlCode(inputLine);
                outputFile.write(inputLine);
            }
        } catch (IOException e) {
            logger.log(Level.FATAL, "Can`t open/read html page.");
        }
    }

    @Override
    public List<URL> getURLList() {
        return urlList;
    }
}
